package com.guliguli.guliguliproduct.service.impl;

import com.guliguli.guliguliproduct.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guliguli.guligulicommon.utils.PageUtils;
import com.guliguli.guligulicommon.utils.Query;

import com.guliguli.guliguliproduct.dao.CategoryDao;
import com.guliguli.guliguliproduct.entity.CategoryEntity;
import com.guliguli.guliguliproduct.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectListAll();
        //System.out.println(entities.toString());

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenusByCid(List<Long> asList) {
        //TODO 检查删除当前菜单，有哪些依赖
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List<CategoryEntity> listWithTreeNoStream() {
        //1、查出所有分类
        //List<CategoryEntity> entities = baseMapper.selectList(null);      selectListAll
        List<CategoryEntity> entities = baseMapper.selectListAll();
        List<CategoryEntity> parent1List = new ArrayList<CategoryEntity>();
        for (CategoryEntity categoryEntity : entities) {
            if (categoryEntity.getParentCid() == 0) {
                parent1List.add(categoryEntity);
            }

        }
        for (CategoryEntity categoryEntity : parent1List) {
            categoryEntity.setChildren(getChildrensByFor(categoryEntity,entities));
        }

        return parent1List;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);

        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    /**
     * 递归查找当前节点父节点
     * @param catelogId 当前节点id
     * @param paths 需要加到的路径
     * @return 节点路径
     */

    private List<Long> findParentPath(Long catelogId,List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * 使用传统方法查出子节点
     * @param root 父节点
     * @param all 需要遍历的所有节点
     * @return 返回有父子结构的list
     */
    private static List<CategoryEntity> getChildrensByFor(CategoryEntity root, List<CategoryEntity> all) {
        ArrayList<CategoryEntity> childrenList = new ArrayList<>();
        for (CategoryEntity categoryEntity : all) {
            if (root.getCatId() == categoryEntity.getParentCid()) {
                root.setChildren(getChildrensByFor(categoryEntity,all));
                childrenList.add(categoryEntity);
            }

        }
        return childrenList;
    }
    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //找到每个分类的子分类
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2、菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
        }

}


